# !/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import re
from modelEtl.modeBase import modeBase
import hashlib
from config import dmp
import requests
import json
from updateConf.borough import borough
from updateConf.cityArea import cityArea

class taiyue(modeBase):
    def __init__(self, source, data, redis):
        data = self.ListDelNull(data)
        super(taiyue, self).__init__()

        self.phone = self._phone(data[0])  # 客源手机号
        self.source_id = source  # 数据来源
        self.user_id = 0 #客源id
        self.imei = str(data[1])  # 【×】
        self.idfa = str(data[2])  # 【×】
        self.city = self._house_city(data[9]) # 客源所在城市
        self.search_term = data[4]  # 所搜词【×】
        self.user_behavior = data[5]  # 用户行为【×】
        self.page_type = data[6]  # 房源类型（1：新房，2：二手房）【×】
        self.visit_time = self.jdtounixToDate(data[7])  # 访问时间【×】
        self.house_province = data[8]  # 房源所在省份【×】
        self.house_city = self._house_city(data[9]) #房源所在市【×】
        self.house_name = data[10] #房源名称【×】
        self.borough_name_source = data[11]  # 小区名称

        #self.borough_id = 0  # 小区id
        self.unit_price = self._unit_price(data[12]) #单价,单价元/平方米(float, 2)【×】
        self.house_price = self._house_price(data[13]) #总价，单位万元(float, 2)
        self.house_room = self._house_room(data[14])  # 室/居
        self.house_hall = self._house_hall(data[14])  # 厅
        self.house_toilet = self._house_toilet(data[14])  # 卫生间
        self.house_totalarea = self._house_totalarea(data[15]) #面积(float, 2)
        self.house_toward = self._house_toward(data[16])
        self.house_topfloor = self._house_topfloor(data[17]) #总楼层
        self.house_floor = self._house_floor(data[17]) #所在楼层
        self.house_fitment = data[18] #装修情况
        self.building_type = data[19] #建筑类型
        self.house_type = data[20] #住宅类型（普通住宅,别墅）
        self.property_right = data[21] #产权
        self.house_address = data[22] # 房源地址
        # self.ctime = int(time.time()) #创建时间

        # 方法
        self._borough(data[11], redis)
        self.queryCity(redis)

    def _unit_price(self, data):
        group = re.findall("(\d+(\.\d+)?)", str(data))

        result = 0.0
        if len(group) > 0: result = group[0][0]
        return float(result)

    def _house_city(self, data):
        city = {
            "上海": "sh",
            "深圳": "sz",
            "深圳": "sz",
            "武汉": "wh",
            "武汉": "wh",
            "成都": "cd",
            "成都": "cd",
            "南京": "nj",
            "南京": "nj",
            "天津": "tj",
            "天津": "tj",
            "杭州": "hz",
            "杭州": "hz",
            "重庆": "cq",
            "重庆": "cq",
            "沈阳": "sy",
            "沈阳": "sy",
            "大连": "dl",
            "大连": "dl",
            "青岛": "qd",
            "青岛": "qd",
            "苏州": "suzhou",
            "三亚": "sanya",
            "郑州": "zz",
            "广州": "gz",
            "济南": "jn",
            "昆明": "km",
            "长春": "cc",
            "西安": "xa",
            "哈尔滨": "heb",
            "长沙": "cs"
        }

        return city.get(data, "")

    def _house_room(self, data):
        group = re.findall("(\d+)室", str(data))

        result = 0
        if len(group) > 0: result = group[0]
        return result

    def _house_hall(self, data):
        group = re.findall("(\d+)厅",str(data))

        result = 0
        if len(group) > 0: result = group[0]
        return result

    def _house_toilet(self, data):
        group = re.findall("(\d+)卫", str(data))

        result = 0
        if len(group) > 0: result = group[0]
        return result


    # def _house_totalarea(self, data):
    #     return ""

    def _house_toward(self, data):
        """
        #朝向,
        1:东  2:西  3:南  4:北
        5:东南  6:西南  7:东北  8:西北
        9:南北  10:东西  11:东西南  12:东南北
        13:西南北 14:东西北 15:东南西北
        :param data:
        :return:
        """
        toward = {
            "东" : 1,
            "西" : 2,
            "南" : 3,
            "北" : 4,
            "东南" : 5,
            "西南" : 6,
            "东北" : 7,
            "西北" : 8,
            "南北" : 9,
            "东西" : 10,
            "东西南" : 11,
            "东南北" : 12,
            "西南北" : 13,
            "东西北" : 14,
            "东南西北" : 15,
        }
        return toward.get(data, 0)

    def _house_topfloor(self, data):
        group = re.findall("共(\d+).*", str(data))

        result = 0
        if len(group) > 0: result = group[0]
        return result

    def _house_floor(self, data):
        group = re.findall(".*(高|中|低)[层|/].*", str(data))

        result = ""
        if len(group) > 0: result = group[0]
        return result

    def _phone(self, data):
        group = re.findall("(\d+)", str(data))

        result = ""
        if len(group) > 0: result = group[0]
        return result

    def _house_price(self, data):
        group = re.findall("(\d+(\.\d+)?)", str(data))
        result = 0.0
        if len(group) > 0: result = group[0][0]
        return float(result)

    def _house_totalarea(self, data):
        if not data: data = 0.0
        return data


    def _borough(self, data, redis):
        """
        小区id
        :param data:
        :param redis:
        :return:
        """
        boroughKey = "borough_%s" % self.house_city
        if not redis.exists(boroughKey):
            borough().update(self.house_city)

        rdata = redis.hget(boroughKey, self.md5(data))
        if not rdata:
            self.borough_id = 0
            self.borough_name = ""
        else:
            result = eval(rdata)
            self.borough_id = result.get('id')
            self.borough_name = result.get('name')


    def md5(self, str):
        m2 = hashlib.md5()  # 获取资源
        m2.update(str)  # 生成MD5
        result = m2.hexdigest()  # 获取MD5
        return result


    def queryCity(self, redis):
        data = {"text" : self.house_address, "city":self.city}

        url = dmp.queryCityUrl % data
        result = requests.get(url=url).content
        rs = json.loads( result )

        #商圈
        if rs.has_key("cityarea2"):
            cityarea2Key = "cityArea2_%s" % self.house_city
            if not redis.exists(cityarea2Key):
                cityArea().update( self.house_city )
                self.cityarea2_name_source = rs.get("cityarea2")

            rdata = redis.hget( cityarea2Key, self.md5( rs.get("cityarea2") ) )
            if not rdata:
                self.cityarea2_id = 0
            else:
                result = eval(rdata)
                self.cityarea2_id = result.get('id')
                self.cityarea2_name = result.get("name")
                self.cityarea2_name_source = result.get("name")
                self.cityarea_id = result.get("pid")
                self.cityarea_name = result.get('pname')
                self.cityarea_name_source = result.get('pname')


        #城区
        if rs.has_key("cityarea") and self.cityarea_id == 0:
            self.cityarea_name_source = rs.get("cityarea")

            cityareaKey = "cityArea_%s" % self.house_city
            if not redis.exists(cityareaKey):
                cityArea().update(self.house_city)

            rdata = redis.hget(cityareaKey, self.md5(rs.get("cityarea")))
            if not rdata:
                self.cityarea_id = 0
                self.cityarea_name =""
            else:
                result = eval(rdata)
                self.cityarea_id = result.get('id')
                self.cityarea_name = result.get('name')
        #小区
        if rs.has_key("borough") and self.borough_id == 0:
            self.borough_name_source = rs.get("borough")

            boroughKey = "borough_%s" % self.house_city
            if not redis.exists(boroughKey):
                borough().update(self.house_city)

            rdata = redis.hget(boroughKey, self.md5(rs.get("borough")))
            if not rdata:
                self.borough_id = 0
                self.borough_name = ""
            else:
                result = eval(rdata)
                self.borough_id = result.get('id')
                self.borough_name = result.get("name")











